package authattemptimpl

import (
	"context"
	"errors"
	"go-caipu/pkg/services/auth/authattempt"
	"gorm.io/gorm"
	"time"
)

type ormStore struct {
	db *gorm.DB
}

type store interface {
	CreateLoginAttempt(ctx context.Context, cmd CreateLoginAttemptCommand) (authattempt.LoginAttempt, error)
	DeleteOldLoginAttempts(ctx context.Context, cmd DeleteOldLoginAttemptsCommand) (int64, error)
	DeleteLoginAttempts(ctx context.Context, cmd DeleteLoginAttemptsCommand) error
	GetUserLoginAttemptCount(ctx context.Context, query GetUserLoginAttemptCountQuery) (int64, error)
}

func (l *ormStore) CreateLoginAttempt(ctx context.Context, cmd CreateLoginAttemptCommand) (authattempt.LoginAttempt, error) {
	result := authattempt.LoginAttempt{
		Username:  cmd.Username,
		IpAddress: cmd.IpAddress,
		Created:   time.Now().Unix(),
	}
	if err := l.db.Create(&result); err != nil {
		return result, errors.New("create auth-attempt error")
	}
	return result, nil
}
func (l *ormStore) DeleteOldLoginAttempts(ctx context.Context, cmd DeleteOldLoginAttemptsCommand) (int64, error) {
	result := l.db.Exec("DELETE FROM login_attempt WHERE created < ?", cmd.OlderThan.Unix())
	return result.RowsAffected, result.Error
}
func (l *ormStore) DeleteLoginAttempts(ctx context.Context, cmd DeleteLoginAttemptsCommand) error {
	result := l.db.Exec("DELETE FROM login_attempt WHERE username < ?", cmd.Username)
	return result.Error
}

func (l *ormStore) GetUserLoginAttemptCount(ctx context.Context, query GetUserLoginAttemptCountQuery) (int64, error) {
	var count int64
	result := l.db.Model(authattempt.LoginAttempt{}).Where("username =? and created>=?", query.Username, query.Since.Unix()).Count(&count)
	return count, result.Error
}
